#!/usr/bin/env bash

set -e

# shellcheck source=helpers source-path=SCRIPTDIR
. "${0%/*}/helpers"

if [ "${BR_CARGO_MANIFEST_PATH}" ]; then
    printf 'Setting BR_CARGO_MANIFEST_PATH is no longer supported; use post-process options.\n' >&2
    exit 1
fi

manifest=Cargo.toml
while getopts "n:o:m:" OPT; do
    case "${OPT}" in
    o)  output="${OPTARG}";;
    n)  base_name="${OPTARG}";;
    m)  manifest="${OPTARG}";;
    :)  error "option '%s' expects a mandatory argument\n" "${OPTARG}";;
    \?) error "unknown option '%s'\n" "${OPTARG}";;
    esac
done

# Already vendored tarball, nothing to do
if tar tf "${output}" | grep -q "^[^/]*/VENDOR" ; then
    exit 0
fi

post_process_unpack "${base_name}" "${output}"

# Do the Cargo vendoring
pushd "${base_name}" > /dev/null

# Create the local .cargo/config.toml with vendor info
mkdir -p .cargo/
mkdir -p "${CARGO_HOME}"
flock "${CARGO_HOME}"/.br-lock \
cargo vendor \
    --manifest-path "${manifest}" \
    --locked VENDOR \
    > .cargo/config.toml

# "cargo vendor' outputs on stderr a message directing to add some data
# to the project's .cargo/config.toml, data that it outputs on stdout.
# Since we redirect stdout to .cargo/config.toml, the message on stderr
# gets confusing, so instruct the user that it's been handled.
printf '(note: .cargo/config.toml automatically updated by Buildroot)\n\n'

popd > /dev/null

post_process_repack "$(pwd)" "${base_name}" "${output}"
